package org.yun.octopus.base.core;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.yun.octopus.base.annotation.Mark;

import java.lang.reflect.Method;

/**
 * @author liyunfeng31
 */
@Component
public class ListenerProcessor implements BeanPostProcessor {

    protected static final Logger LOG = LoggerFactory.getLogger(ListenerProcessor.class);


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
 
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());

        for (Method method : methods) {
            Mark mark = AnnotationUtils.findAnnotation(method, Mark.class);
            if(mark != null){
                try {
                    Class<?> clz = Class.forName(bean.getClass().getCanonicalName());
                    RollbackFactory.addFallback(clz, mark.group(), mark.stepNo(), mark.rollback(), mark.role());
                }catch (ClassNotFoundException e){
                    LOG.error("Reflection methods fail, beanName:{} ", beanName, e);
                } catch (IllegalAccessException | InstantiationException | NoSuchMethodException e) {
                    LOG.error("addFallback fail, beanName:{}, mark:{} ", beanName, mark, e);
                }
            }
        }
        return bean;
    }
}

